package com.kangfu.api.controller;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.List;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.freewayso.image.combiner.enums.ZoomMode;
import com.kangfu.api.interceptor.AuthorizationInterceptor;
import com.kangfu.api.service.IUserInfoService;
import com.kangfu.api.service.IUserPointService;
import com.kangfu.api.service.IUserService;
import com.kangfu.common.annotation.IgnoreAuth;
import com.kangfu.common.model.AjaxResult;
import com.kangfu.db.domain.entity.User;
import com.kangfu.db.domain.entity.UserPoint;
import com.kangfu.db.mapper.UserMapper;
import com.kangfu.db.model.vo.UserSocreVo;
import gui.ava.html.image.generator.HtmlImageGenerator;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;


/**
 * 用户运动打分Controller
 * 
 * @author ruoyi
 * @date 2022-09-30
 */
@Controller
@RequestMapping("/score")
public class UserPointController
{
    @Autowired
    private IUserPointService userPointService;

    @Autowired
    private IUserService userService;

    @Autowired
    private UserMapper userMapper;

    /**
     * 获取某一周的打分信息
     * @param userId
     * @param page
     * @return
     */
    @GetMapping("/info")
    @ResponseBody
    public AjaxResult getWeekScore(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestParam(name = "page", defaultValue = "1") Integer page) {
        User user = userService.selectUserById(userId);
        UserSocreVo userSocreVo = new UserSocreVo();
        //累计打卡超越人数
        int exceedCount = userMapper.selectExceedCount(user.getCheckinCount());
        if (userId == 119) {
            exceedCount = 21;
        }
        //累计打卡天数
        int checkinCount = user.getCheckinCount();
        if (userId == 119) {
            checkinCount = 30;
        }
        //坚持打卡天数
        int goonCount = user.getGoonCount();
        if (userId == 119) {
            goonCount = 30;
        }
        userSocreVo.setAvatar(user.getAvatar());
        userSocreVo.setNickname(user.getNickname());
        userSocreVo.setCheckinCount(checkinCount);
        userSocreVo.setGoonCount(goonCount);
        userSocreVo.setExceedCount(exceedCount);

        UserPoint userPoint = userPointService.getUserPointByPage(userId, page);
        if (userPoint != null) {
            userSocreVo.setStartDate(userPoint.getStartDate());
            userSocreVo.setEndDate(userPoint.getEndDate());
            userSocreVo.setScore(userPoint.getScore());
        }

        Integer count = userPointService.getCountByUserId(userId);
        userSocreVo.setCount(count);
        return AjaxResult.success(userSocreVo);
    }

    @GetMapping("/img")
    public void img(@RequestAttribute(AuthorizationInterceptor.LOGIN_USER_ID) int userId, @RequestParam(name = "page", defaultValue = "1") Integer page,  HttpServletResponse response) throws Exception {
        User user = userService.selectUserById(userId);
        UserSocreVo userSocreVo = new UserSocreVo();
        //累计打卡超越人数
        int exceedCount = userMapper.selectExceedCount(user.getCheckinCount());
        if (userId == 119) {
            exceedCount = 21;
        }
        //累计打卡天数
        int checkinCount = user.getCheckinCount();
        if (userId == 119) {
            checkinCount = 30;
        }
        //坚持打卡天数
        int goonCount = user.getGoonCount();
        if (userId == 119) {
            goonCount = 30;
        }

        String score = "0.00";
        String startDate = "00.00";
        String endDate = "00.00";

        userSocreVo.setCheckinCount(checkinCount);
        userSocreVo.setGoonCount(goonCount);
        userSocreVo.setExceedCount(exceedCount);

        UserPoint userPoint = userPointService.getUserPointByPage(userId, page);
        if (userPoint != null) {
            score = userPoint.getScore() != null ? userPoint.getScore().toString() : "0.00";
            startDate = userPoint.getStartDate() != null ? LocalDateTimeUtil.format(userPoint.getStartDate(), "MM.dd") : "00.00";
            endDate = userPoint.getEndDate() != null ? LocalDateTimeUtil.format(userPoint.getEndDate(), "MM.dd") : "00.00";
        }
        //生成图片
        //合成器（指定背景图和输出格式，整个图片的宽高和相关计算依赖于背景图，所以背景图的大小是个基准）
        ImageCombiner combiner = new ImageCombiner("https://qny.bravo.love/temp/ic_report.png", OutputFormat.JPG);
        //加图片元素（居中绘制，圆角，半透明）
        combiner.addImageElement(user.getAvatar(), 47, 47, 94, 94, ZoomMode.WidthHeight)
                .setRoundCorner(200);   //圆角

        combiner.addTextElement(user.getNickname(), "微软雅黑", 30, 165, 65)
                .setSpace(.2f)                      //字间距
                .setColor(Color.WHITE);    //颜色

        combiner.addTextElement(score, "微软雅黑", 80, 483, 410)
                .setColor(Color.WHITE);    //颜色

        combiner.addTextElement(startDate + "-" + endDate, "微软雅黑", 40, 450, 697)
                .setColor(Color.BLACK);    //颜色

        combiner.addTextElement(String.valueOf(checkinCount) + " 天", "微软雅黑", 33, 860, 927)
                .setColor(Color.BLACK);    //颜色

        combiner.addTextElement(String.valueOf(goonCount) + " 天", "微软雅黑", 33, 860, 1115)
                .setColor(Color.BLACK);    //颜色

        combiner.addTextElement(String.valueOf(exceedCount) + " 人", "微软雅黑", 33, 860, 1281)
                .setColor(Color.BLACK);    //颜色

        //合成图片
        combiner.combine();
        InputStream is = combiner.getCombinedImageStream();
        FileCopyUtils.copy(is, response.getOutputStream());
    }
}
